#!/bin/bash

# MySQL数据库批量数据插入脚本
# 用于向products表批量插入测试数据

API_URL="http://127.0.0.1:55001/api/classicmodels.products/bulk"
BATCH_SIZE=100
BATCH_COUNT=10
START_PRODUCT_ID=1000

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 产品线数组
product_lines=("Classic Cars" "Motorcycles" "Planes" "Ships" "Trains" "Trucks and Buses" "Vintage Cars")

# 产品厂商数组
product_vendors=(
    "Classic Metal Creations" "Min Lin Diecast" "Highway 66 Mini Classics"
    "Red Start Diecast" "Motor City Art Classics" "Second Gear Diecast"
    "Autoart Studio Design" "Exoto Designs" "Welly Diecast Productions"
    "Unimax Art Galleries" "Studio M Art Models" "Carousel DieCast Legends"
)

# 产品名称前缀数组
product_prefixes=(
    "1969" "1970" "1971" "1972" "1973" "1974" "1975" "1976" "1977" "1978"
    "1980" "1985" "1990" "1995" "2000" "2005" "Classic" "Vintage" "Deluxe"
)

# 产品名称主体数组
product_names=(
    "Ford Mustang" "Chevrolet Camaro" "Dodge Challenger" "Ferrari 250 GT" "Porsche 911"
    "Lamborghini Countach" "BMW M3" "Mercedes SL" "Jaguar E-Type" "Aston Martin DB5"
    "Harley Davidson" "Honda CBR" "Yamaha YZF" "Kawasaki Ninja" "Ducati Monster"
    "Boeing 747" "Airbus A380" "Cessna 172" "P-51 Mustang" "Spitfire"
)

# 产品比例数组
product_scales=("1:10" "1:12" "1:18" "1:24" "1:32" "1:43" "1:50" "1:64")

# 日志函数
log() {
    echo -e "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# 错误处理
error_exit() {
    log "${RED}错误: $1${NC}"
    exit 1
}

# 显示帮助信息
show_help() {
    echo "MySQL数据库批量数据插入脚本"
    echo ""
    echo "用法:"
    echo "  $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -s, --start-id <ID>     起始product_id (默认: $START_PRODUCT_ID)"
    echo "  -b, --batch-size <SIZE> 每批数据量 (默认: $BATCH_SIZE)"
    echo "  -c, --batch-count <COUNT> 批次数量 (默认: $BATCH_COUNT)"
    echo "  -u, --url <URL>         API地址 (默认: $API_URL)"
    echo "  -h, --help              显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0                      # 使用默认参数"
    echo "  $0 -s 2000 -b 50 -c 5   # 从2000开始，每批50条，共5批"
}

# 生成随机价格
generate_price() {
    local buy_price=$(echo "scale=2; ($RANDOM % 20000 + 1000) / 100" | bc) # $10.00 - $210.00
    local msrp=$(echo "scale=2; $buy_price * (150 + $RANDOM % 100) / 100" | bc) # 1.5x - 2.5x markup
    
    echo "$buy_price,$msrp"
}

# 获取随机产品线
get_random_product_line() {
    local index=$((RANDOM % ${#product_lines[@]}))
    echo "${product_lines[$index]}"
}

# 获取随机厂商
get_random_vendor() {
    local index=$((RANDOM % ${#product_vendors[@]}))
    echo "${product_vendors[$index]}"
}

# 获取随机比例
get_random_scale() {
    local index=$((RANDOM % ${#product_scales[@]}))
    echo "${product_scales[$index]}"
}

# 生成产品名称
generate_product_name() {
    local prefix_index=$((RANDOM % ${#product_prefixes[@]}))
    local name_index=$((RANDOM % ${#product_names[@]}))
    echo "${product_prefixes[$prefix_index]} ${product_names[$name_index]}"
}

# 生成产品描述
generate_description() {
    local descriptions=(
        "High quality die-cast model with exceptional detail and craftsmanship."
        "Features opening doors, detailed interior, and working steering."
        "Precision engineered replica with authentic markings and logos."
        "Collector's edition model with superior paint finish and chrome details."
        "Hand-crafted model featuring realistic proportions and fine details."
    )
    local index=$((RANDOM % ${#descriptions[@]}))
    echo "${descriptions[$index]}"
}

# 生成单批数据JSON
generate_batch_data() {
    local start_id=$1
    local batch_size=$2
    local json="["

    for ((i = 0; i < batch_size; i++)); do
        local product_id=$((start_id + i))
        local product_code="P$product_id"
        local product_name=$(generate_product_name)
        local product_line=$(get_random_product_line)
        local product_scale=$(get_random_scale)
        local product_vendor=$(get_random_vendor)
        local product_description=$(generate_description)
        local quantity_in_stock=$((RANDOM % 9000 + 1000)) # 1000-10000
        local price_info=$(generate_price)
        local buy_price=$(echo "$price_info" | cut -d',' -f1)
        local msrp=$(echo "$price_info" | cut -d',' -f2)

        # 构建JSON对象
        local product_json="{\"productCode\":\"$product_code\",\"productName\":\"$product_name\",\"productLine\":\"$product_line\",\"productScale\":\"$product_scale\",\"productVendor\":\"$product_vendor\",\"productDescription\":\"$product_description\",\"quantityInStock\":$quantity_in_stock,\"buyPrice\":$buy_price,\"MSRP\":$msrp}"

        if [ $i -eq 0 ]; then
            json="$json$product_json"
        else
            json="$json,$product_json"
        fi
    done

    json="$json]"
    echo "$json"
}

# 执行批量插入
execute_batch_insert() {
    local batch_num=$1
    local json_data=$2

    log "${BLUE}执行第 $batch_num 批数据插入...${NC}"

    # 使用curl发送POST请求
    response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "Content-Type: application/json" \
        -d "$json_data" \
        "$API_URL" 2>/dev/null)

    # 分离响应体和状态码
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)

    if [ "$http_code" -eq 200 ] || [ "$http_code" -eq 201 ]; then
        log "${GREEN}✓ 第 $batch_num 批插入成功 (HTTP $http_code)${NC}"
        return 0
    else
        log "${RED}✗ 第 $batch_num 批插入失败 (HTTP $http_code)${NC}"
        log "${YELLOW}响应: $response_body${NC}"
        return 1
    fi
}

# 参数解析
while [[ $# -gt 0 ]]; do
    case $1 in
    -s | --start-id)
        START_PRODUCT_ID="$2"
        shift 2
        ;;
    -b | --batch-size)
        BATCH_SIZE="$2"
        shift 2
        ;;
    -c | --batch-count)
        BATCH_COUNT="$2"
        shift 2
        ;;
    -u | --url)
        API_URL="$2"
        shift 2
        ;;
    -h | --help)
        show_help
        exit 0
        ;;
    *)
        echo "未知参数: $1"
        show_help
        exit 1
        ;;
    esac
done

# 参数验证
if ! [[ "$START_PRODUCT_ID" =~ ^[0-9]+$ ]] || [ "$START_PRODUCT_ID" -lt 1 ]; then
    error_exit "起始job_id必须是正整数"
fi

if ! [[ "$BATCH_SIZE" =~ ^[0-9]+$ ]] || [ "$BATCH_SIZE" -lt 1 ]; then
    error_exit "批量大小必须是正整数"
fi

if ! [[ "$BATCH_COUNT" =~ ^[0-9]+$ ]] || [ "$BATCH_COUNT" -lt 1 ]; then
    error_exit "批次数量必须是正整数"
fi

# 检查依赖
if ! command -v curl &>/dev/null; then
    error_exit "curl 未安装，请先安装 curl"
fi

# 显示配置信息
log "${GREEN}===== MySQL数据库批量数据插入开始 =====${NC}"
log "API地址: $API_URL"
log "起始product_id: $START_PRODUCT_ID"
log "每批数据量: $BATCH_SIZE"
log "批次数量: $BATCH_COUNT"
log "总计数据量: $((BATCH_SIZE * BATCH_COUNT))"
log ""

# 测试API连通性
log "${BLUE}测试API连通性...${NC}"
test_response=$(curl -s -w "%{http_code}" -X GET "http://127.0.0.1:55001/api/classicmodels.products" -o /dev/null)
if [ "$test_response" -eq 200 ]; then
    log "${GREEN}✓ API连通性测试通过${NC}"
else
    log "${YELLOW}⚠ API连通性测试返回HTTP $test_response，继续执行...${NC}"
fi
log ""

# 执行批量插入
successful_batches=0
failed_batches=0
current_product_id=$START_PRODUCT_ID

for ((batch = 1; batch <= BATCH_COUNT; batch++)); do
    log "${BLUE}准备第 $batch 批数据 (product_id: $current_product_id - $((current_product_id + BATCH_SIZE - 1)))${NC}"

    # 生成批量数据
    json_data=$(generate_batch_data "$current_product_id" "$BATCH_SIZE")

    # 显示部分示例数据
    sample_data=$(echo "$json_data" | head -c 200)
    log "示例数据: ${sample_data}..."

    # 执行插入
    if execute_batch_insert "$batch" "$json_data"; then
        ((successful_batches++))
    else
        ((failed_batches++))
    fi

    # 更新下一批的起始ID
    current_product_id=$((current_product_id + BATCH_SIZE))

    log ""
done

# 显示结果统计
log "${GREEN}===== 批量插入完成 =====${NC}"
log "总批次: $BATCH_COUNT"
log "成功批次: $successful_batches"
log "失败批次: $failed_batches"
log "成功插入数据: $((successful_batches * BATCH_SIZE)) 条"

if [ $failed_batches -eq 0 ]; then
    log "${GREEN}🎉 所有数据插入成功！${NC}"
    exit 0
else
    log "${YELLOW}⚠ 有 $failed_batches 个批次插入失败${NC}"
    exit 1
fi
